[1, 2, 3].map(function(n) { return n * 2; }, this);
// -> [ 2, 4, 6 ]
ES6:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var evens = [2, 4, 6, 8, 10];
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
console.log(odds);
// -> [3, 5, 7, 9, 11]
console.log(nums);
// -> [2, 5, 8, 11, 14]
// Statement bodies
var fives = [];
nums = [1, 2, 5, 15, 25, 32];
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
console.log(fives);
// -> [5, 15, 25]
// Lexical this
var bob = {
_name: 'Bob',
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + ' knows ' + f));
}
}
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'use strict';
var evens = [2, 4, 6, 8, 10];
// Expression bodies
var odds = evens.map(function (v) {
return v + 1;
}, this);
var nums = evens.map(function (v, i) {
return v + i;
}, this);
console.log(odds);
// -> [3, 5, 7, 9, 11]
console.log(nums);
// -> [2, 5, 8, 11, 14]
var fives = [];
nums = [1, 2, 5, 15, 25, 32];
// Statement bodies
nums.forEach(function (v) {
if (v % 5 === 0) {
fives.push(v);
}
}, this);
console.log(fives);
// -> [5, 15, 25]
// Lexical this
var bob = {
_name: 'Bob',
_friends: [],
printFriends: functionprintFriends() {
this._friends.forEach(function (f) {
returnconsole.log(this._name + ' knows ' + f);
}, this);
}
};
Block Scoping Functions
Block scoped bindings provide scopes other than the function and top level scope. This ensures your variables don’t leak out of the scope they’re defined:
ES6:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// let declares a block scope local variable,
// optionally initializing it to a value in ES6
'use strict';
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // The scope is inside the if-block
var b = 1; // The scope is inside the function
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1
//let再es5中使用闭包实现
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'use strict';
var a = 5;
var b = 10;
if (a === 5) {
// technically is more like the following
(function () {
var a = 4;
b = 1;
console.log(a); // 4
console.log(b); // 1
})();
}
console.log(a); // 5
console.log(b); // 1
ES6:
1
2
3
4
5
6
7
8
9
10
11
// const creates a read-only named constant in ES6.
'use strict';
// define favorite as a constant and give it the value 7
const favorite = 7;
// Attempt to overwrite the constant
try {
favorite = 15;
} catch (err) {
console.log('my favorite number is still: ' + favorite);
// will still print 7
}
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict';
// define favorite as a non-writable `constant` and give it the value 7
Object.defineProperties(window, {
favorite: {
value: 7,
enumerable: true
}
});
// ^ descriptors are by default false and const are enumerable
var favorite = 7;
// Attempt to overwrite the constant
favorite = 15;
// will still print 7
console.log('my favorite number is still: ' + favorite);
Template Literals
ES6 Template Literals are strings that can include embedded expressions. This is sometimes referred to as string interpolation.
ES6:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Basic usage with an expression placeholder
var person = 'Addy Osmani';
console.log(`Yo! My name is ${person}!`);
// Expressions work just as well with object literals
var user = {name: 'Caitlin Potter'};
console.log(`Thanks for getting this into V8, ${user.name}.`);
// Expression interpolation. One use is readable inline math.
var a = 50;
var b = 100;
console.log(`The number of JS frameworks is ${a + b} and not ${2 * a + b}.`);
// Multi-line strings without needing \n\
console.log(`string text line 1
string text line 2`);
// Functions inside expressions
functionfn() { return'result'; }
console.log(`foo ${fn()} bar`);
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'use strict';
// Basic usage with an expression placeholder
var person = 'Addy Osmani';
console.log('Yo! My name is ' + person + '!');
// Expressions work just as well with object literals
var user = { name: 'Caitlin Potter' };
console.log('Thanks for getting this into V8, ' + user.name + '.');
// Expression interpolation. One use is readable inline math.
var a = 50;
var b = 100;
console.log('The number of JS frameworks is ' + (a + b) + ' and not ' + (2 * a + b) + '.');
// Multi-line strings:
console.log('string text line 1\nstring text line 2');
// Or, alternatively:
console.log('string text line 1\n\
string text line 2');
// Functions inside expressions
functionfn() {
return'result';
}
console.log('foo ' + fn() + ' bar');
Computed Property Names
Computed property names allow you to specify properties in object literals based on expressions:
ES6:
1
2
3
4
5
6
7
8
9
10
var prefix = 'foo';
var myObject = {
[prefix + 'bar']: 'hello',
[prefix + 'baz']: 'world'
};
console.log(myObject['foobar']);
// -> hello
console.log(myObject['foobaz']);
// -> world
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
'use strict';
var prefix = 'foo';
var myObject = {};
myObject[prefix + 'bar'] = 'hello';
myObject[prefix + 'baz'] = 'world';
console.log(myObject['foobar']);
// -> hello
console.log(myObject['foobaz']);
// -> world
Destructuring Assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
ES6:
1
2
var {foo, bar} = {foo: 'lorem', bar: 'ipsum'};
// foo => lorem and bar => ipsum
ES5:
1
2
3
4
5
6
7
'use strict';
var _ref = { foo: 'lorem', bar: 'ipsum' };
// foo => lorem and bar => ipsum
var foo = _ref.foo;
var bar = _ref.bar;
ES3:
1
2
3
4
5
6
7
8
9
10
11
with({foo: 'lorem', bar: 'ipsum'}) {
// foo => lorem and bar => ipsum
}
···
ES6:
```javascript
var [a, , b] = [1,2,3];
ES6:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'use strict';
var _slicedToArray = function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
return name ? ('var ' + name + '=slice(' + i + ', ' + (i + 1) + ')[0]') : '';
}).join(';');
};
with([1,2,3]) {
eval('a, , b'.asNamedList());
}
Default Parameters
Default parameters allow your functions to have optional arguments without needing to check arguments.length or check for undefined.
ES6:
1
2
3
4
5
6
7
8
functiongreet(msg='hello', name='world') {
console.log(msg,name);
}
greet();
// -> hello world
greet('hey');
// -> hey world
ES5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'use strict';
functiongreet() {
// unfair ... if you access arguments[0] like this you can simply
// access the msg variable name instead
var msg = arguments[0] === undefined ? 'hello' : arguments[0];
var name = arguments[1] === undefined ? 'world' : arguments[1];
console.log(msg, name);
}
functiongreet(msg, name) {
(msg === undefined) && (msg = 'hello');
(name === undefined) && (name = 'world');
console.log(msg,name);
}
// using basic utility that check against undefined
functiongreet(msg, name) {
console.log(
defaults(msg, 'hello'),
defaults(name, 'world')
);
}
greet();
// -> hello world
greet('hey');
// -> hey world
ES6:
1
2
3
4
5
6
functionf(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) === 15;
ES5:
1
2
3
4
5
6
7
8
9
10
11
'use strict';
functionf(x, y) {
if (y === undefined) {
y = 12;
}
return x + y;
}
f(3) === 15;
Iterators And For-Of
Iterators are objects that can traverse a container. It’s a useful way to make a class work inside a for of loop. The interface is similar to the iterators-interface. Iterating with a for..of loop looks like:
ES6:
1
2
3
4
5
// Behind the scenes, this will get an iterator from the array and loop through it, getting values from it.
for (let element of [1, 2, 3]) {
console.log(element);
}
// => 1 2 3
ES6(without using for-of, if Symbol is supported):
// Doesn't require declaring indexing and element variables in your containing
// scope. They get supplied as arguments to the iterator and are scoped to just
// that iteration.
var a = [1,2,3];
a.forEach(function (element) {
console.log(element);
});
// => 1 2 3
// Using a for loop
var a = [1,2,3];
for (var i = 0; i < a.length; ++i) {
console.log(a[i]);
}
// => 1 2 3
Note the use of Symbol. The ES5 equivalent would require a Symbol polyfill in order to correctly function.
Classes
This implements class syntax and semantics as described in the ES6 draft spec. Classes are a great way to reuse code. Several JS libraries provide classes and inheritance, but they aren’t mutually compatible.
A more faithful (albeit, slightly verbose) interpretation can be found in this Babel output.
Modules
Modules are mostly implemented, with some parts of the Loader API still to be corrected. Modules try to solve many issues in dependencies and deployment, allowing users to create modules with explicit exports, import specific exported names from those modules, and keep these names separate.